package com.zeildlin.seecode.Service;


import com.zeildlin.seecode.Dao.Mapper.LoginTicketMapper;
import com.zeildlin.seecode.Dao.Mapper.UserMapper;
import com.zeildlin.seecode.entity.LoginTicket;
import com.zeildlin.seecode.entity.User;
import com.zeildlin.seecode.util.CommunitConstant;
import com.zeildlin.seecode.util.CommunityUtil;
import com.zeildlin.seecode.util.MailClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService implements CommunitConstant {
    private  static final Logger logger = LoggerFactory.getLogger("LoginController");

    @Autowired
    UserMapper userMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private LoginTicketMapper loginTicketMapper;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${communty.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    public User FindUserById(int userid){
        return userMapper.getUserById(userid);
    }


    /*
    注册
     */
    public Map<String,Object> register(User user)  {
        Map<String,Object>map = new HashMap<>();

        //控制异常处理
        if(user == null){
            throw new IllegalArgumentException("参数不能为空");
        }
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg","账号不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg","密码不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())){
            map.put("EmailMsg","邮箱不能为空");
            return map;
        }
        //验证账号
        User u = userMapper.getUserByName(user.getUsername());
        if(u != null){
            map.put("userMsg","账号已存在");
            return map;
        }
        //验证邮箱
        u = userMapper.getUserByEmail(user.getEmail());
        if(u != null){
            map.put("emailMsg","邮箱已被注册！");
            return map;
        }

        //注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0,5));
        user.setPassword(CommunityUtil.md5(user.getPassword()+user.getSalt()));


        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generateUUID().substring(0,4));
        user.setHeaderUrl("http://api.dujin.org/bing/1920.php");
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        //激活邮件
        Context context = new Context();
        context.setVariable("email",user.getEmail());
        context.setVariable("username",user.getUsername());
        //http://localhost:8080/seecode/activation/101/code
        String url = domain+contextPath+"/activation"+user.getId()+"/"+user.getActivationCode();
        context.setVariable("url",url);
        String content = templateEngine.process("/mail/activation",context);
        mailClient.sendMail(user.getEmail(),"激活账户",content);


        return map;
    }

    public int activation(int userId,String code){
        User user = userMapper.getUserById(userId);
        if(user.getStatus() == 1){
            return ACTIVATION_REPEAT;
        }else if(user.getActivationCode().equals(code)){
            userMapper.updateUserStatus(userId,1);
            return ACTIVATION_SUCCESS;
        }else{
            return ACTIVATION_FAILURE;
        }
    }

    public Map<String ,Object> LoginTicket(String username,String password,int expiredSecond){
        Map<String,Object>map = new HashMap<>();
        //检查空值
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg","用户名不能为空！");
            return map;
        }
        if(StringUtils.isBlank(password)){
            map.put("passwordMsg","密码不能为空！");
            return map;
        }

        //检查登陆信息
        User user = userMapper.getUserByName(username);


        //验证用户名是否正确
        if(user == null){
            map.put("usernameMsg","用户名错误！");
            return map;
        }
        //验证用户注册状态
        if(user.getStatus()==0){
            map.put("usernameMsg","该账号未激活！");
            return map;
        }


        //验证密码是否正确
        //user.setPassword(CommunityUtil.md5(user.getPassword()+user.getSalt()));
        if(!user.getPassword().equals(CommunityUtil.md5(password+user.getSalt()))){
            map.put("passwordMsg","密码错误！");
            return map;
        }
        // 生成登陆凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserid(user.getId());
        loginTicket.setExpired(new Date(System.currentTimeMillis()+expiredSecond * 1000));
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicketMapper.insertLoginTicket(loginTicket);
        map.put("ticket",loginTicket.getTicket());
        return map;
    }

    public void logout(String Ticket){
        loginTicketMapper.updateStatus(Ticket,1);
    }
    public LoginTicket findLoginTicket(String ticket){
        return loginTicketMapper.selectbyTicket(ticket);
    }

    public int updateHeader(int userId, String headerUrl) {
        return userMapper.updateUserHeader(userId, headerUrl);
    }

    public User findUserByName(String username) {
        return userMapper.getUserByName(username);
    }

}
